package cn.common.config;



import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author effortjiang
 * @date 2020-05-07
 */
/**
 * Copyright
 *
 * @Author WuHuang
 * @Date 2022/12/22
 */
@Component
public class TsrSpringContextAware implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    private static Long startTime = System.currentTimeMillis();
    private static String appName = "";


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        TsrSpringContextAware.applicationContext = applicationContext;
    }

    /**
     * 获取上下文
     *
     * @return Spring上下文
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取Spring配置
     *
     * @param key 配置名称
     * @return 配置值
     */
    public static String getProperties(String key) {
        return applicationContext.getEnvironment().getProperty(key);
    }

    /**
     * 获取Spring配置<br>
     * 没有配置时，返回默认值
     *
     * @param key          配置名称
     * @param defaultValue 默认值
     * @return 配置值
     */
    public static String getProperties(String key, String defaultValue) {
        return applicationContext.getEnvironment().getProperty(key, defaultValue);
    }

    public static <T> T getBean(Class<T> requiredType) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(requiredType);
    }


    public static String getAppName() {
        return appName;
    }

    public static void setAppName(String appName) {
        TsrSpringContextAware.appName = appName;
    }


    public static Long getStartTime() {
        return startTime;
    }

    public static void setStartTime(Long startTime) {
        TsrSpringContextAware.startTime = startTime;
    }

}

